package com.baitiaojun.system.admin.controller.captcha;

import com.baitiaojun.common.constants.Constants;
import com.baitiaojun.common.domain.model.result.CommonResult;
import com.baitiaojun.common.utils.id.IdUtils;
import com.baitiaojun.common.utils.io.IoUtils;
import com.baitiaojun.common.utils.sign.Base64;
import com.baitiaojun.ratelimit.core.annotation.RateLimit;
import com.baitiaojun.redis.core.support.RedisSupport;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api("验证码")
@RequestMapping("/admin/captcha")
@RestController
public class CaptchaController {

    @Resource(name = "captchaProducer")
    private DefaultKaptcha captchaProducer;

    @Autowired
    private RedisSupport redisSupport;

    @ApiOperation("获取验证码")
    @RateLimit(key = "captcha", count = 3, time = 1, RATE_LIMIT_TYPE = RateLimit.RateLimitType.IP)
    @GetMapping("/captchaImage")
    public CommonResult getCaptcha() {
        //生成验证码
        String text = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(text);

        //redis缓存
        String id = IdUtils.fastSimpleUUID();
        redisSupport.addValue(Constants.CAPTCHA_CODE_KEY, id, text, 5L, TimeUnit.MINUTES);

        //编译成base64字符串
        String imageBase64Str = Base64.encode(IoUtils.toByte(image));

        //返回验证码和captchaId
        Map<String, Object> data = new HashMap<>();
        data.put("captchaId", id);
        data.put("captcha", imageBase64Str);
        return CommonResult.ok(data);
    }
}
